<script setup>
import { ref, onMounted, computed } from 'vue'
import { sessionApi, treeTypeApi, pageInfoApi, oneInfoApi, saveInfoApi, procInfosApi, sortInfoApi } from '@/common/api'
import router from '@/common/router'
import Note from '@/components/notify'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import { CScrollbar } from 'c-scrollbar'
import Pager from '@/components/pagination/UbtPager.vue'
import { formatDateRange } from "@/common/filter"
import Datepicker from '@vuepic/vue-datepicker'
import '@vuepic/vue-datepicker/dist/main.css'
import UbtTreeSel from '@/components/cascader/UbtTreeSel.vue'
import UbtSelect from '@/components/select/UbtSelect.vue'
import UbtUpload from '@/components/upload/UbtUpload.vue'
import UbtTag from '@/components/tag/UbtTag.vue'

// 自动加载，判断权限
onMounted(() => {
  checkAuth()
})

// 资讯种类 1表示内容资讯，2表示视频资讯
const infoKind = 1

const procAuth = ref({
  addAuth: false,
  delAuth: false,
  edtAuth: false
})
// checkAuth 获取权限
const checkAuth = async () => {
  const res = await sessionApi()
  if (res.code === 200) {
    const userBtnCode = res.data.btnCodes
    procAuth.value = {
      addAuth: userBtnCode.indexOf('1002010301') !== -1,
      delAuth: userBtnCode.indexOf('1002010302') !== -1,
      edtAuth: userBtnCode.indexOf('1002010303') !== -1,
      pasAuth: userBtnCode.indexOf('1002010304') !== -1,
      unpAuth: userBtnCode.indexOf('1002010305') !== -1
    }
    list(0, 1)
    selType()
  } else {
    Msg({ kind: 'error', txt: res.msg })
    router.replace('/login')
  }
}

const schDate = ref([])
const dateForm = ref([])
const schObj = {
  schName: '',
  kind: infoKind,
  infoType: '',
  typeName: '',
  typeCode: '',
  states: 0,
  stateName: '',
  stateCode: '',
  beginTime: 0,
  endTime: 0,
  offset: 0,
  limit: 20
}
const schRef = ref(schObj)
const total = ref(0)
const curPage = ref(1)
const infoList = ref([])
const hasData = ref(false)
const checkList = ref([])
// list 列表展示
const list = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  schRef.value.beginTime = schDate.value && schDate.value.length===2 && schDate.value[0] ? schDate.value[0].getTime()/1000 : 0
  schRef.value.endTime = schDate.value && schDate.value.length===2 && schDate.value[1] ? schDate.value[1].getTime()/1000 : 0
  const res = await pageInfoApi(schRef.value)
  if(res.code === 200 && res.data) {
    hasData.value = true
    total.value = res.data.total
    infoList.value = res.data.list
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.list.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    schName: '',
    kind: infoKind,
    infoType: '',
    typeName: '',
    typeCode: '',
    states: 0,
    stateName: '',
    stateCode: '',
    beginTime: 0,
    endTime: 0,
    offset: 0,
    limit: 20
  }
  schDate.value = []
  list(0, 1)
}

// 选择效果实现
const idList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    infoList.value.forEach(item => {
      idList.value.push(item.infoId)
      checkList.value.push(true)
    })
  } else {
    infoList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, infoId) => {
  if(!checkList.value[idx]) {
    idList.value.push(infoId)
  } else {
    const index = idList.value.findIndex(id => {
      if(id === infoId){
        return true
      }
    })
    idList.value.splice(index, 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const infoObj = {
  infoId: '',
  fstTitle: '',
  secTitle: '',
  kind: infoKind,
  infoType: '',
  typeName: '',
  typeCode: '',
  sort: 0,
  src: '优佰通',
  beginTime: 0,
  endTime: 0,
  cmted: 2,
  describ: '',
  contents: '',
  fstImgId: '',
  fstImgName: '',
  fstImgUrl: '',
  imgIds: '',
  imgNames: '',
  imgUrls: '',
  fileIds: '',
  fileNames: '',
  fileUrls: '',
  visitNum: 0,
  goodNum: 0,
  cmtNum: 0,
  tagIds: '',
  tagNames: '',
}
const infoForm = ref(infoObj)
// add 新增
const showModal = ref(false)
const add = () => {
  showModal.value = true
}

const imgRef = ref()
const imgListRef = ref([])
const fileListRef = ref([])
const infoStr = ref('')

// update 修改
const update = async (infoId) => {
  const res = await oneInfoApi({infoId})
  if(res.code === 200) {
    showModal.value = true
    infoForm.value = res.data
    // 设置起止时间
    const beginDate = new Date(infoForm.value.beginTime * 1000)
    const endDate = new Date(infoForm.value.endTime * 1000)
    dateForm.value.push(beginDate)
    dateForm.value.push(endDate)
    // 加载首图
    if(infoForm.value.fstImgId && infoForm.value.fstImgId!=='') {
      imgRef.value = {id: infoForm.value.fstImgId, name: infoForm.value.fstImgName, url: infoForm.value.fstImgUrl, thumb: infoForm.value.fstImgUrl.replace('/img', '/img/thumb')}
    }
    // 加载多图
    if(infoForm.value.imgIds && infoForm.value.imgIds!=='') {
      let imgIdArr = infoForm.value.imgIds.split(',')
      let imgNameArr = infoForm.value.imgNames.split(',')
      let imgUrlArr = infoForm.value.imgUrls.split(',')
      for(let i=0, c=imgIdArr.length; i<c; i++) {
        imgListRef.value.push({id: imgIdArr[i], name: imgNameArr[i], url: imgUrlArr[i], thumb: imgUrlArr[i].replace('/img', '/img/thumb')})
      }
    }
    // 加载多附件
    if(infoForm.value.fileIds && infoForm.value.fileIds!=='') {
      let fileIdArr = infoForm.value.fileIds.split(',')
      let fileNameArr = infoForm.value.fileNames.split(',')
      let fileUrlArr = infoForm.value.fileUrls.split(',')
      for(let i=0, c=fileIdArr.length; i<c; i++) {
        fileListRef.value.push({id: fileIdArr[i], name: fileNameArr[i], url: fileUrlArr[i]})
      }
    }
    // 加载内容
    infoStr.value = infoForm.value.contents
    // 加载标签
    if(infoForm.value.tagIds && infoForm.value.tagIds!=='') {
      tagIdArr.value = infoForm.value.tagIds.split(',')
      tagNameArr.value = infoForm.value.tagNames.split(',')
    }
  }
}
// save 保存提交
const save = async () => {
  // 校验
  let fstTitle = infoForm.value.fstTitle
  let infoType = infoForm.value.infoType
  let sort = infoForm.value.sort
  let src = infoForm.value.src
  let dates = dateForm.value
  if(fstTitle === '' || fstTitle.length > 80) {
    Msg({ kind: 'warn', txt: '标题不能为空，且长度不超过80个字符！' })
    return
  }
  if(infoType === '' || infoType.length !== 21) {
    Msg({ kind: 'warn', txt: '分类不能为空，请选择资讯分类！' })
    return
  }
  if(sort === '' || sort === '0') {
    Msg({ kind: 'warn', txt: '资讯排序不能为空，请输入！' })
    return
  }
  if(src === '' || src.length > 80) {
    Msg({ kind: 'warn', txt: '资讯来源不能为空！' })
    return
  }
  if(!dates || dates.length !== 2) {
    Msg({ kind: 'warn', txt: '请选择资讯的发布日期和截止日期！' })
    return
  }
  // 转数字
  infoForm.value.sort = parseInt(sort)
  let num = infoForm.value.cmtNum
  infoForm.value.cmtNum = parseInt(num)
  num = infoForm.value.goodNum
  infoForm.value.goodNum = parseInt(num)
  num = infoForm.value.visitNum
  infoForm.value.visitNum = parseInt(num)
  // 起止时间转换为时间戳
  infoForm.value.beginTime = dateForm.value && dateForm.value.length===2 && dateForm.value[0] ? dateForm.value[0].getTime()/1000 : 0
  infoForm.value.endTime = dateForm.value && dateForm.value.length===2 && dateForm.value[1] ? dateForm.value[1].getTime()/1000 : 0
  // 设置首图
  if(imgRef.value && imgRef.value.id) {
    infoForm.value.fstImgId = imgRef.value.id
    infoForm.value.fstImgName = imgRef.value.name
    infoForm.value.fstImgUrl = imgRef.value.url
  }
  // 设置多图
  let imgIds='', imgNames='', imgUrls=''
  imgListRef.value.forEach(curImg => {
    imgIds += curImg.id + ','
    imgNames += curImg.name + ','
    imgUrls += curImg.url + ','
  })
  imgIds = imgIds.substring(0, imgIds.length-1)
  imgNames = imgNames.substring(0, imgNames.length-1)
  imgUrls = imgUrls.substring(0, imgUrls.length-1)
  infoForm.value.imgIds = imgIds
  infoForm.value.imgNames = imgNames
  infoForm.value.imgUrls = imgUrls
  // 设置多附件
  let fileIds='', fileNames='', fileUrls=''
  fileListRef.value.forEach(curfile => {
    fileIds += curfile.id + ','
    fileNames += curfile.name + ','
    fileUrls += curfile.url + ','
  })
  fileIds = fileIds.substring(0, fileIds.length-1)
  fileNames = fileNames.substring(0, fileNames.length-1)
  fileUrls = fileUrls.substring(0, fileUrls.length-1)
  infoForm.value.fileIds = fileIds
  infoForm.value.fileNames = fileNames
  infoForm.value.fileUrls = fileUrls
  // 设置内容
  infoForm.value.contents = infoStr.value
  // 提交信息
  const res = await saveInfoApi(infoForm.value)
  if(res.code === 200) {
    closeModal()
    list(0, 1)
    Note({ kind: 'success', title: '成功', txt: '恭喜您，资讯信息保存成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// closeModal 关闭弹出层，并重置表单资讯
const closeModal = () => {
  showModal.value = false
  infoForm.value = {
    infoId: '',
    fstTitle: '',
    secTitle: '',
    kind: infoKind,
    infoType: '',
    typeName: '',
    typeCode: '',
    sort: 0,
    src: '优佰通',
    beginTime: 0,
    endTime: 0,
    cmted: 2,
    describ: '',
    contents: '',
    fstImgId: '',
    fstImgName: '',
    fstImgUrl: '',
    imgIds: '',
    imgNames: '',
    imgUrls: '',
    fileIds: '',
    fileNames: '',
    fileUrls: '',
    visitNum: 0,
    goodNum: 0,
    cmtNum: 0,
    tagIds: '',
    tagNames: '',
  }
  infoStr.value = ''
  dateForm.value = []
  imgRef.value = null
  imgListRef.value = []
  fileListRef.value = []
  tagIdArr.value = []
  tagNameArr.value = []
}

// process 删除资讯
const process = async(states) => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再操作！' })
    return
  }
  Confirm('确定要删除选中的资讯吗？').then(() => {
    procInfos(states)
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消处理选中的资讯！" })
  })
}
// procInfos 删除资讯实现，分离出来防止调用时异步报错
const procInfos = async (states) => {
  let infoIds = idList.value.join(',')
  const res = await procInfosApi({ infoIds, states, kind: infoKind })
  if(res.code === 200) {
    list(0, 1)
    Note({ kind: 'success', title: '成功', txt: '恭喜您，资讯信息处理成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// fmtDateRange 起止时间戳转时间
const fmtDateRange = computed(() => {
  return (beginTime, endTime, kind) => {
    let beginDate = new Date(beginTime*1000)
    let endDate = new Date(endTime*1000)
    let dateArr = [beginDate, endDate]
    return formatDateRange(dateArr, kind)
  }
})

// selType 获取分类下拉列表
const typeList = ref([])
const selType = async () => {
  const res = await treeTypeApi({kind: 3})
  if(res.code === 200) {
    typeList.value = res.data
  }
}

// 状态数组静态值
const stateList = [{selId: 1, selName: '上架', selCode: '101', chked: false}, {selId: 3, selName: '下架', selCode: '103', chked: false}]

// 设置下拉框的值
const setValue = (item, kind) => {
  switch(kind) {
    case 1:
      schRef.value.infoType = item.selId
      schRef.value.typeName = item.selName
      schRef.value.typeCode = item.selCode
      break
    case 2:
      sort(item.selId)
      infoForm.value.infoType = item.selId
      infoForm.value.typeName = item.selName
      infoForm.value.typeCode = item.selCode
      break
    case 3:
      schRef.value.states = item.selId
      schRef.value.stateName = item.selName
      schRef.value.stateCode = item.selCode
      break
  }
}

// sort 按钮排序
const sort = async (infoType) => {
  const res = await sortInfoApi({ infoType })
  if(res.code === 200) {
    infoForm.value.sort = res.data
  }
}

// stateFmt 状态转码
const stateFmt = computed(() => {
  return (states) => {
    let str
    switch (states) {
      case 1:
        str = '上线'
        break;
      case 3:
        str = '下线'
        break;
      default:
        str = '其它'
        break
    }
    return str
  }
})

// 开关效果
const chkCmted = (idx) => {
  switch(idx) {
    case 1:
      infoForm.value.cmted = 1
      break
    case 2:
      infoForm.value.cmted = 2
      break
    default:
      infoForm.value.cmted = 1
      break
  }
}

// 获取图片信息
const setUrl = (kind, types, file) => {
  switch (kind) {
    case 1:
      imgRef.value = file
      break
    case 2:
      imgListRef.value = file
      break
    case 4:
      fileListRef.value = file
      break
  }
}

// 内容正文
const setContents = (contents) => {
  infoStr.value = contents
}

// 标签
const tagIdArr = ref([])
const tagNameArr = ref([])
const setTags = (idArr, nameArr) => {
  tagIdArr.value = idArr
  tagNameArr.value = nameArr
  infoForm.value.tagIds = tagIdArr.value.join(',')
  infoForm.value.tagNames = tagNameArr.value.join(',')
}
</script>

<template>
  <div class="a">
    <!-- 头部资讯 -->
    <div class="b">
      <div v-if="procAuth.addAuth" class="btn-p" title="新增" @click="add()"><i class="iconfont doc_text"></i> 新增</div>
      <div v-if="procAuth.delAuth" class="btn-d" title="删除" @click="process(2)"><i class="iconfont trash"></i> 删除</div>
      <div v-if="procAuth.pasAuth" class="btn-d" title="上线" @click="process(1)"><i class="iconfont text_badge_checkmark"></i> 上线</div>
      <div v-if="procAuth.unpAuth" class="btn-d" title="下线" @click="process(3)"><i class="iconfont text_badge_xmark"></i> 下线</div>
      <div class="btn-r" title="筛选" @click="search()"><i class="iconfont search"></i></div>
      <div class="btn-r" title="刷新" @click="list(0, 1)"><i class="iconfont arrow__circlepath"></i></div>
    </div>
    <!-- 中部资讯 -->
    <div class="c" v-if="schShow">
      <div class="d"><ubt-tree-sel :tree-list="typeList" :kind="1" :inboxed="true" :curName="schRef.typeName!=='' ? schRef.typeName+'['+schRef.typeCode+']' : ''" pre-name="分类" @setValue="setValue" /></div>
      <div class="d"><ubt-select :kind="3" :sel-list="stateList" :inboxed="true" :curName="schRef.stateName!=='' ? schRef.stateName+'['+schRef.stateCode+']' : ''" pre-name="状态" @setValue="setValue" /></div>
      <div class="d"><input type="text" v-model="schRef.schName" placeholder="请输入关键字" class="e" /></div>
      <div class="d"><Datepicker v-model="schDate" range locale="zh-CN" :format="formatDateRange" style="width: 250px;" placeholder="请选择筛选时间段"></Datepicker></div>
      <div class="f">
        <div class="btn-p" @click="list(0, 1)"><i class="iconfont search"></i> 筛选</div>
        <div class="btn-d" @click="clrSch()"><i class="iconfont arrow_turn_up_left"></i> 重置</div>
      </div>
    </div>
    <div class="g" v-if="hasData">
      <table>
        <tr>
          <th style="width: 5%;"><i @click="checkAll()" :class="['iconfont', allCheck ? 'checkmark_square_fill chked' : 'app chk']"></i></th>
          <th style="width: 40%;">标题</th>
          <th style="width: 15%;">分类</th>
          <th style="width: 20%;">时间</th>
          <th style="width: 10%;">状态</th>
          <th style="width: 10%;">操作</th>
        </tr>
        <tr v-for="(curInfo, index) in infoList" :key="curInfo.infoId" class="tr-style">
          <td class="txt-center"><i @click="checkCurId(index, curInfo.infoId)" :class="['iconfont', checkList[index] ? 'checkmark_square_fill chked' : 'app chk']"></i></td>
          <td :title="curInfo.fstTitle">{{curInfo.fstTitle}}</td>
          <td class="txt-center">{{curInfo.typeName}}</td>
          <td class="txt-center">{{fmtDateRange(curInfo.beginTime, curInfo.endTime, 1)}}</td>
          <td class="txt-center">{{stateFmt(curInfo.states)}}</td>
          <td class="txt-center">
            <span v-if="procAuth.edtAuth" class="cl-blue" title="修改" @click="update(curInfo.infoId)"><i class="iconfont square_pencil"></i> 修 改</span>
          </td>
        </tr>
      </table>
      <Pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="list" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 1000px">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont doc_plaintext fs20"></i> 保存资讯信息</div>
              <div class="header-right" @click="closeModal()"><i class="iconfont xmark fs20"></i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>资讯标题</div>
                <div><input type="text" v-model="infoForm.fstTitle" maxlength="80" placeholder="请输入资讯标题" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title">资讯副标题</div>
                <div><input type="text" v-model="infoForm.secTitle" maxlength="80" placeholder="请输入资讯副标题" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>资讯分类</div>
                <ubt-tree-sel :tree-list="typeList" :kind="2" :inboxed="false" :curName="infoForm.typeName ? infoForm.typeName+'['+infoForm.typeCode+']' : ''" pre-name="所属分类" @setValue="setValue" />
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>资讯排序</div>
                <div style="display: block;"><input type="text" v-model="infoForm.sort" maxlength="11" placeholder="请输入排序" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>资讯来源</div>
                <div><input type="text" v-model="infoForm.src" maxlength="50" placeholder="请输入资讯来源" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>起止时间</div>
                <div><Datepicker v-model="dateForm" range locale="zh-CN" :format="formatDateRange" style="width: 100%;" placeholder="请选择起止时间段"></Datepicker></div>
              </div>
              <div>
                <div class="ipt-title">开启评论</div>
                <div class="h">
                  <div class="cur i" @click="chkCmted(1)"><i :class="['iconfont', infoForm.cmted===1 ? 'largecircle_fill_circle chked' : 'circle chk']"></i> 开启</div>
                  <div class="cur i" @click="chkCmted(2)"><i :class="['iconfont', infoForm.cmted===1 ? 'circle chk' : 'largecircle_fill_circle chked']"></i> 关闭</div>
                </div>
              </div>
              <div>
                <div class="ipt-title">资讯首图</div>
                <div><ubt-upload :kind="1" :types="1" :file="imgRef" @setUrl="setUrl" /></div>
              </div>
              <div>
                <div class="ipt-title">资讯图片</div>
                <div><ubt-upload :kind="2" :types="1" :files="imgListRef" @setUrl="setUrl" /></div>
              </div>
              <div>
                <div class="ipt-title">资讯附件</div>
                <div><ubt-upload :kind="4" :types="1" :files="fileListRef" @setUrl="setUrl" /></div>
              </div>
              <div>
                <div class="ipt-title">资讯描述</div>
                <div><textarea v-model="infoForm.describ" class="desc-txt"></textarea></div>
              </div>
              <div>
                <div class="ipt-title">资讯内容</div>
                <div><ubt-editor :contents="infoStr" @setContents="setContents" /></div>
              </div>
              <div>
                <div class="ipt-title">访问数量</div>
                <div><input type="text" v-model="infoForm.visitNum" maxlength="11" placeholder="请输入访问数量" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title">点赞数量</div>
                <div><input type="text" v-model="infoForm.goodNum" maxlength="11" placeholder="请输入点赞数量" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title">评论数量</div>
                <div><input type="text" v-model="infoForm.cmtNum" maxlength="11" placeholder="请输入评论数量" class="txt" /></div>
              </div>
              <div>
                <div class="ipt-title">资讯标签</div>
                <div><UbtTag :tagIdArr="tagIdArr" :tagNameArr="tagNameArr" :kind="1" @setTags="setTags" /></div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-p" @click="save()"><i class="iconfont today_fill"></i> 保存</div>
              <div class="btn-d" @click="closeModal()"><i class="iconfont arrowshape_turn_up_left"></i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
  </div>
</template>

<style scoped>
.a {width: 100%; height: 100%;}
.b {padding: 10px 20px; display: flex; display: -webkit-flex;}
.c {margin: 0 10px 10px 10px; border: 1px solid #CCC; display: flex; display: -webkit-flex; padding: 0 15px 15px 15px; flex-wrap: wrap; justify-content: flex-end;}
.d {flex-grow: 1; margin-top: 15px;}
.e {width: 230px; padding: 8px;}
.f {display: flex; display: -webkit-flex; padding-top: 15px;}
.g {background-color: #FFF;}
.h {display: flex; display: -webkit-flex;}
.i {width: 80px; margin: 10px;}
</style>
